import copy
from utils.conf import Response
from rest_framework.views import APIView
from ChatGPTServer.settings import formatResponseData, _request


class Infinigo(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = []
    # 局部(本视图有效)权限类
    permission_classes = []

    def post(self, request, *args, **kwargs):
        """
        Infinigo接口
        """
        data = copy.deepcopy(formatResponseData)
        try:
            question = request.data.get("question")

            # 异常拦截
            if not question:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            # sennuo爬虫
            headers = {
                'Accept': 'application/json, text/plain, */*',
                'Cookie': 'ip=1; sajssdk_2015_cross_new_user=1; sensorsdata2015jssdkcross=t',
                'Host': 'www.infinigo.com',
                'Referer': 'https://www.infinigo.com/icchat?source=PCBYL',
                'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Mobile Safari/537.36'
            }

            response = _request.get(headers=headers,
                                    url=f'https://www.infinigo.com/api/openai/complete?text={question}')
            answer = response.json()["data"]["answer"]

            data["data"]["answer"] = answer
            return Response(data=data, loggerMsg=f"Infinigo接口响应成功：question={question}")

        except Exception as e:
            return Response(data=data, loggerMsg=f"Infinigo接口响应失败：{e}", isError=True)
